/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx.utils;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * <p>Project: javaweb - DbUtil
 * <p>Powered by webrx On 2022-03-11 09:18:01
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class DbUtil {
    private DruidDataSource ds;
    private QueryRunner run;

    public DbUtil() {
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties");
        Properties prop = new Properties();
        try {
            prop.load(is);
            this.ds = new DruidDataSource();
            this.ds.setDriverClassName(prop.getProperty("db.driver", "com.mysql.cj.jdbc.Driver"));
            this.ds.setUrl(prop.getProperty("db.url", "jdbc:mysql:"));
            this.ds.setUsername(prop.getProperty("db.username", "root"));
            this.ds.setPassword(prop.getProperty("db.password", ""));
            this.run = new QueryRunner(this.ds);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<String> tbs() {
        List<String> set = new ArrayList<>();
        try {
            set = this.run.query("show tables", new ColumnListHandler<>());
        } catch (Exception e) {
            try {
                set = this.run.query("show tables from mysql", new ColumnListHandler<>());
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
        return set;
    }

    public List<String> tbs(String dbname) {
        List<String> set = new ArrayList<>();
        try {
            set = this.run.query(String.format("show tables from `%s`", dbname), new ColumnListHandler<>());
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        return set;
    }

    public int update(String sql, Object... params) {
        int result = 0;
        try {
            result = this.run.update(sql, params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * Description: 检查能不能登录
     *
     * @date: 2022/3/11 10:10
     * @params: [java.lang.String, java.lang.String]
     * @return: boolean
     */
    public boolean checkLogin(String account, String password) {
        boolean f = false;
        try {
            long t = this.run.query("select count(0) from wx_member where account=? and passwd=?", new ScalarHandler<>(), account, password);
            if(t>0){
                f = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return f;
    }
}
